package main

import (
	"net/http"
	"github.com/julienschmidt/httprouter"
	"log"
)

func main() {
	log.Println("流服务器启动")
	r:=registerHandlers()
	m:=newLimitMiddleware(r,2)
	http.ListenAndServe(":9000",m)
}

func registerHandlers() *httprouter.Router {

	router:=httprouter.New()

	router.GET("/videos/:vid-id",streamHandler)

	router.POST("/upload",uploadHandler2)
	router.POST("/upload/:vid-id",uploadHandler)

	return router
}


type limitMiddleware struct {
	r *httprouter.Router
	limiter *ConnLimiter
}

func newLimitMiddleware(router *httprouter.Router,limit int)*limitMiddleware{

	limiter:=NewConnLimiter(limit)

	return &limitMiddleware{
		r:router,
		limiter:limiter,
	}

}


func (m *limitMiddleware) ServeHTTP(w http.ResponseWriter,r *http.Request){
	if !m.limiter.GetConn(){
		sendErrorResponse(w,http.StatusTooManyRequests,"Too Many Requests")
		return
	}

	defer m.limiter.ReleaseConn()
	m.r.ServeHTTP(w,r)
}





